package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.article.feign.ArticleFeign;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.AuthorDto;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.dtos.UserAuthDto;
import com.usian.user.entity.ApUser;
import com.usian.user.entity.ApUserAuth;
import com.usian.user.mapper.ApUserAuthMapper;
import com.usian.user.service.IApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.user.service.IApUserService;
import com.usian.wemedia.feign.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-05
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements IApUserAuthService {

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {
        if (dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //构建分页条件
        Page<ApUserAuth> page = new Page<>(dto.getPage(),dto.getSize());
        //构建查询条件 基于频道名称模糊查询
        QueryWrapper<ApUserAuth> queryWrapper = new QueryWrapper<>();
        if(dto.getStatus()!=null){
            // where name like '%java%'
            queryWrapper.lambda().eq(ApUserAuth::getStatus,dto.getStatus());
            //queryWrapper.like("name",name);
        }
        //执行查询
        IPage<ApUserAuth> iPage = page(page, queryWrapper);
        List<ApUserAuth> records = iPage.getRecords();
        //封装查询结果
        if(CollectionUtils.isEmpty(records)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"审核用户不存在");
        }
        //将AdChannel结果集转为ChannelDto
        List<UserAuthDto> channelDtoList = BeanHelper.copyWithCollection(records, UserAuthDto.class);

        return new PageResult<UserAuthDto>(dto.getPage(),dto.getSize(),iPage.getTotal(),channelDtoList);
    }


    @Autowired
    private IApUserService iApUserService;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Override
    @GlobalTransactional//开启全局事务控制（分布式事务控制）
    public void updateAuthStatus(AuthDto authDto, int status) {
        //0、参数校验
        if (authDto==null || authDto.getId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //审核状态参数校验
        if (status!=ApUserAuth.Status.FAIL.getCode() && status!=ApUserAuth.Status.PASS.getCode()) {
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"审核状态必须是2活9");
        }

        //1、修改用户状态
        ApUserAuth apUserAuth = new ApUserAuth();
        Integer authId = authDto.getId();
        apUserAuth.setId(authId);
        apUserAuth.setStatus(status);
        apUserAuth.setReason(authDto.getMsg());
        boolean b = updateById(apUserAuth);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新审核状态失败");
        }
        //2、判断认证状态，是否是通过

        //2.1、如果审核通过，创建自媒体账号和作者账号
        if (status==ApUserAuth.Status.FAIL.getCode()){
            return;
        }
        //2.2、如果失败，更新失败的原因
        //先获取app用户id
        ApUserAuth userAuth = getById(authId);
        Integer userId = userAuth.getUserId();
        //查询app用户信息
        ApUser apUser = iApUserService.getById(userId);
        //        远程调用wemedia，创建自媒体用户，传递WmUserDto对象
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setName(apUser.getName());
        wmUserDto.setImage(apUser.getImage());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setApUserId(userId);
        wmUserDto.setStatus(status);
        //查询是否存在自媒体用户
        WmUserDto wmUserDto1 = wemediaFeign.findByApUserId(userId);
        if (wmUserDto1==null){
            //自媒体用户不存在，创建自媒体用户
            Integer wmUserId = wemediaFeign.saveWmUser(wmUserDto);
            //将返回得自媒体用户id设置到dto中，方便保存作者信息是否关联自媒体信息
            wmUserDto.setId(wmUserId);
        }
        //创建自媒体用户
        AuthorDto authorDto=new AuthorDto();
        authorDto.setUserId(userId);
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        authorDto.setWmUserId(wmUserDto.getId());
        //查询是否存在作者
        AuthorDto authorDto1 = articleFeign.findByUserId(userId);
        if (authorDto1==null){
            //保存作者信息
            articleFeign.saveApAuthor(authorDto);
        }

        //修改用户标识，是否是自媒体人
        //跟新用户类型
        ApUser apUser1 = new ApUser();
        apUser1.setId(userId);
        apUser1.setFlag(1);
        boolean b1 = iApUserService.updateById(apUser1);
        if (!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新用户标识失败");
        }
//        int i=1/0;
    }
}
